package com.leyou.page.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.BrandDTO;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpuDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class PageService {

    @Autowired
    private ItemClient itemClient;

    @Value("${ly.static.itemDir}")
    private String itemDir;

    @Value("${ly.static.itemTemplate}")
    private String itemTemplate;

    @Autowired
    private SpringTemplateEngine templateEngine;

    public Map<String,Object> loadItemPage(Long id) {
        //根据spuId查询spu对象
        SpuDTO spuDTO = itemClient.querySpuById(id);
        //查询出分类集合
        List<Long> categoryIds = spuDTO.getCategoryIds();
        //查询出三级分类的对象
        List<CategoryDTO> categoryDTOList = itemClient.queryCategoryByIds(categoryIds);
        //用spuDTO里面的brandID查
        BrandDTO brandDTO = itemClient.queryById(spuDTO.getBrandId());
        //根据spuDTO里面cid3去查询
        List<SpecGroupDTO> specGroupDTOList = itemClient.findSpecGroupByCid(spuDTO.getCid3());


        Map<String, Object> itemMap = new HashMap<>();
        itemMap.put("spuName", spuDTO.getName());//商品名称 string,spuDTO里面
        itemMap.put("detail",spuDTO.getSpuDetail());//spuDetail对象,spuDTO里面
        itemMap.put("skus", spuDTO.getSkus());//sku的列表,spuDTO里面
        itemMap.put("subTitle", spuDTO.getSubTitle());//商品副标题 string,spuDTO里面
        itemMap.put("categories",categoryDTOList);//分类列表,spuDTO里面getCategoryIds
        itemMap.put("brand", brandDTO);//品牌对象,用spuDTO里面的brandID查
        itemMap.put("specs", specGroupDTOList);//规格组的集合,根据spuDTO里面cid3去查询
        return itemMap;
    }

    public void createItemHtml(Long id){
        try {
            //封装上下文
            Context context = new Context();
            context.setVariables(loadItemPage(id));
            //得到要输出的路径文件
            File sourceFile = new File(itemDir);
            //创建出当前静态页面文件
            File itemFile = new File(sourceFile, id + ".html");
            //得到文件打印流
            PrintWriter printWriter = new PrintWriter(itemFile);
            //生成静态页面
            templateEngine.process(itemTemplate, context, printWriter);
            log.info("生成商品静态页面成功！！");
        } catch (Exception e) {
            log.error("生成商品静态页面失败！！");
            throw new LyException(ExceptionEnum.DIRECTORY_WRITER_ERROR);
        }
    }

    public void deleteItemHtml(Long id) {
        File file = new File(itemDir, id + ".html");
        if (file.exists()) {
            if (!file.delete()) {
                log.error("【静态页服务】静态页删除失败，商品id：{}", id);
                throw new LyException(ExceptionEnum.FILE_WRITER_ERROR);
            }
        }
    }
}
